const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

console.log('🔍 服务器数据库连接调试脚本');
console.log('=====================================');
console.log('');

// 1. 检查环境信息
console.log('📋 1. 环境信息检查:');
console.log('   当前工作目录:', process.cwd());
console.log('   Node.js 版本:', process.version);
console.log('   操作系统:', process.platform);
console.log('   进程 ID:', process.pid);
console.log('');

// 2. 检查 .env 文件
console.log('📋 2. .env 文件检查:');
const envPaths = [
  path.join(process.cwd(), '.env'),
  path.join(__dirname, '.env'),
  '/www/wwwroot/server/text-tags-backend/.env'
];

let envFileFound = false;
for (const envPath of envPaths) {
  console.log(`   检查路径: ${envPath}`);
  if (fs.existsSync(envPath)) {
    console.log(`   ✅ 找到 .env 文件`);
    try {
      const content = fs.readFileSync(envPath, 'utf8');
      console.log(`   文件大小: ${content.length} 字节`);
      console.log(`   文件内容预览:`);
      const lines = content.split('\n').filter(line => line.trim());
      lines.forEach(line => {
        if (line.includes('PASSWORD')) {
          console.log(`     ${line.split('=')[0]}=***HIDDEN***`);
        } else {
          console.log(`     ${line}`);
        }
      });
      envFileFound = true;
      break;
    } catch (error) {
      console.log(`   ❌ 读取文件失败: ${error.message}`);
    }
  } else {
    console.log(`   ❌ 文件不存在`);
  }
}

if (!envFileFound) {
  console.log('   ⚠️  未找到 .env 文件');
}
console.log('');

// 3. 检查环境变量
console.log('📋 3. 环境变量检查:');
const envVars = ['NODE_ENV', 'DB_HOST', 'DB_PORT', 'DB_USERNAME', 'DB_PASSWORD', 'DB_DATABASE'];
envVars.forEach(envVar => {
  const value = process.env[envVar];
  if (envVar === 'DB_PASSWORD') {
    console.log(`   ${envVar}: ${value ? '***SET***' : 'NOT SET'}`);
  } else {
    console.log(`   ${envVar}: ${value || 'NOT SET'}`);
  }
});
console.log('');

// 4. 尝试加载 .env 文件
console.log('📋 4. 尝试加载 .env 文件:');
try {
  const dotenv = require('dotenv');
  const result = dotenv.config();
  if (result.error) {
    console.log('   ❌ 加载失败:', result.error.message);
  } else {
    console.log('   ✅ 加载成功');
    console.log('   加载后环境变量:');
    envVars.forEach(envVar => {
      const value = process.env[envVar];
      if (envVar === 'DB_PASSWORD') {
        console.log(`     ${envVar}: ${value ? '***SET***' : 'NOT SET'}`);
      } else {
        console.log(`     ${envVar}: ${value || 'NOT SET'}`);
      }
    });
  }
} catch (error) {
  console.log('   ❌ dotenv 模块加载失败:', error.message);
}
console.log('');

// 5. 测试数据库连接
console.log('📋 5. 数据库连接测试:');
async function testDatabaseConnection() {
  const connectionConfig = {
    host: process.env.DB_HOST || '49.51.193.79',
    port: parseInt(process.env.DB_PORT) || 3306,
    user: process.env.DB_USERNAME || 'prompt',
    password: process.env.DB_PASSWORD || '42SSH3Br6AH2RsJ2',
    database: process.env.DB_DATABASE || 'prompt',
    connectTimeout: 10000,
    acquireTimeout: 10000,
    timeout: 10000
  };

  console.log('   连接配置:');
  console.log(`     主机: ${connectionConfig.host}`);
  console.log(`     端口: ${connectionConfig.port}`);
  console.log(`     用户: ${connectionConfig.user}`);
  console.log(`     密码: ${connectionConfig.password ? '***SET***' : 'NOT SET'}`);
  console.log(`     数据库: ${connectionConfig.database}`);
  console.log('');

  try {
    console.log('   ⏳ 尝试连接数据库...');
    const connection = await mysql.createConnection(connectionConfig);
    console.log('   ✅ 数据库连接成功！');
    
    // 测试查询
    console.log('   ⏳ 测试查询...');
    const [rows] = await connection.execute('SELECT 1 as test, NOW() as now_time');
    console.log('   ✅ 查询成功:', rows[0]);
    
    // 检查表
    console.log('   ⏳ 检查数据库表...');
    const [tables] = await connection.execute('SHOW TABLES');
    console.log('   ✅ 数据库表:', tables.map(t => Object.values(t)[0]));
    
    await connection.end();
    console.log('   ✅ 连接已关闭');
    
  } catch (error) {
    console.log('   ❌ 数据库连接失败:');
    console.log(`     错误代码: ${error.code}`);
    console.log(`     错误消息: ${error.message}`);
    console.log(`     错误堆栈: ${error.stack}`);
    
    // 提供具体的解决建议
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('   🔧 访问被拒绝 - 建议检查:');
      console.log('     - 用户名和密码是否正确');
      console.log('     - 用户是否有权限连接');
      console.log('     - 是否允许从当前IP连接');
    } else if (error.code === 'ECONNREFUSED') {
      console.log('   🔧 连接被拒绝 - 建议检查:');
      console.log('     - MySQL服务是否运行');
      console.log('     - 端口3306是否开放');
      console.log('     - 防火墙设置');
    } else if (error.code === 'ETIMEDOUT') {
      console.log('   🔧 连接超时 - 建议检查:');
      console.log('     - 网络连接');
      console.log('     - MySQL是否接受远程连接');
      console.log('     - 安全组/防火墙设置');
    }
  }
}

testDatabaseConnection().then(() => {
  console.log('');
  console.log('=====================================');
  console.log('🎯 调试完成');
}).catch(error => {
  console.log('');
  console.log('=====================================');
  console.log('❌ 调试脚本执行失败:', error.message);
});
